package com.kaiwukj.android.ufamily.mvp.ui.page.home.message;

import android.content.Context;
import android.os.Bundle;
import android.util.Pair;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerChatComponent;
import com.kaiwukj.android.ufamily.hx.DemoHelper;
import com.kaiwukj.android.ufamily.mvp.contract.ChatContract;
import com.kaiwukj.android.ufamily.mvp.http.entity.base.EventMessage;
import com.kaiwukj.android.ufamily.mvp.http.entity.event.EMClientStateEvent;
import com.kaiwukj.android.ufamily.mvp.http.entity.resultbak.CommunityGroupResult;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MessageListFragment extends BaseMvpFragment<ChatPresenter> implements ChatContract.View, DemoHelper.OnMessageRefreshListener {

  /*  @BindView(R.id.container_left)
    ViewGroup containerLeft;
    @BindView(R.id.container_right)
    ViewGroup containerRight;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.tv_title)
    TextView tvTitle;*/

    @BindView(R.id.smart_refresh_view_chat)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_chat_contract)
    RecyclerView rvMsg;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;

    private MessageListAdapter mListAdapter;

    private boolean isConflict;

    public static MessageListFragment newInstance() {
        Bundle args = new Bundle();
        MessageListFragment fragment = new MessageListFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerChatComponent.builder()
                .appComponent(appComponent)
                .view(this)
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chat;
    }

    @Override
    protected void initView() {
       /* containerLeft.setVisibility(View.GONE);
        containerRight.setVisibility(View.VISIBLE);
        tvRight.setBackgroundResource(R.mipmap.ic_msg_friend_add);
        containerRight.setOnClickListener(v -> ARouter.getInstance()
                .build(ARouterUrlKt.MessageSearchUrl).navigation());
        tvTitle.setText("消息");*/

        rvMsg.setLayoutManager(new LinearLayoutManager(getContext()));
        mListAdapter = new MessageListAdapter();
        rvMsg.setAdapter(mListAdapter);

        mListAdapter.setOnEventListener(new MessageListAdapter.OnEventListener() {
            @Override
            public void onKeeperClick(View view) {
                String keeperHxName = getApp().getUserInfo().getKeeperHxName();
                if (!StringUtils.isEmpty(keeperHxName)) {
                    ChatActivity.startKeeperChat(getCtx(), keeperHxName);
                } else {
                    ARouter.getInstance().build(ARouterUrlKt.MineKeeperContainerUrl).navigation();
                    // showMessage("管家信息获取失败");
                }
            }

            @Override
            public void onAboutMeClick(View view) {
                ARouter.getInstance()
                        .build(ARouterUrlKt.DynamicAboutMeUrl)
                        .navigation();
            }
        });

        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mListAdapter.addChatData(loadConversationList(), true);
                refreshLayout.finishRefresh(1800);
            }
        });

    }

    @Override
    protected void initData(Bundle savedInstanceState) {

        //  setPaddingTop(R.id.root_view);

        DemoHelper.getInstance().setOnMessageRefreshListener(this);

        EMClient.getInstance().addConnectionListener(connectionListener);

        List<MessageMultiItemEntity> entityList = new ArrayList<>();
        MessageMultiItemEntity keeperEntity = new MessageMultiItemEntity();
        keeperEntity.setKeeperConversation(null);
        keeperEntity.setItemType(MessageMultiItemEntity.KEEPER);

        MessageMultiItemEntity noticeEntity = new MessageMultiItemEntity();
        noticeEntity.setItemType(MessageMultiItemEntity.MSG_NOTICE);

        MessageMultiItemEntity chatEntity = new MessageMultiItemEntity();
        chatEntity.setChatList(loadConversationList());
        chatEntity.setItemType(MessageMultiItemEntity.CHAT);

        entityList.add(keeperEntity);
        entityList.add(noticeEntity);
        entityList.add(chatEntity);

        mListAdapter.setList(entityList);
        //emptyView.show(true);
        // mListAdapter.addChatData(loadConversationList(), true);
    }

    private String getKeeperNewMessage() {
        String keeperHXName = getApp().getUserInfo().getKeeperHxName();
        if (!StringUtils.isEmpty(keeperHXName)) {
            EMConversation conversation = EMClient.getInstance().chatManager().getConversation(keeperHXName);
            if (conversation != null) {
                EMMessage lastMessage = conversation.getLastMessage();
                if (lastMessage != null) {
                    return EaseCommonUtils.getMessageDigest(lastMessage, (this.getContext()));
                }
            }
        }

        return "";

    }

    @Override
    public void onResume() {
        super.onResume();
        //mListAdapter.addChatData(loadConversationList(), true);
    }

    private EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                //handler.sendEmptyMessage(0);
                EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.Disconnected));
            }
        }

        @Override
        public void onConnected() {
            //handler.sendEmptyMessage(1);
            EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.Connected));
        }

    };

    @Override
    public void onMessageRefreshListener() {
        // refreshLayout.autoRefresh();
        LogUtils.d("---------------onMessageRefresh----------------");
        //mListAdapter.addChatData(loadConversationList(), true);
        //  EventBus.getDefault().post(new EMClientStateEvent(EMClientStateEvent.MSG_REFRESH));
        refreshConversation();
    }

    @Override
    public Context getCtx() {
        return getContext();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (isConflict) {
            outState.putBoolean("isConflict", true);
        }
    }

    @Override
    public void onGetNoticeList(List<CommunityGroupResult> list) {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onStateEvent(EMClientStateEvent event) {
        switch (event.getState()) {
            case EMClientStateEvent.Disconnected:
                onConnectionDisconnected();
                break;
            case EMClientStateEvent.Connected:
                onConnectionConnected();
                break;
            case EMClientStateEvent.MSG_REFRESH:
                //hasRefresh = true;
//                    List<EMConversation> list = loadConversationList();
//                    for (int i = 0; i < list.size(); i++) {
//                        if (!list.get(i).isGroup()) {
//                            conversationList.add(list.get(i));
//                        }
//                    }
                refreshConversation();

                break;
        }
    }

    /**
     * connected to server
     */
    protected void onConnectionConnected() {
        //errorItemContainer.setVisibility(View.GONE);
        LogUtils.d("聊天服务器已连接");
    }

    /**
     * disconnected with server
     */
    protected void onConnectionDisconnected() {
        //errorItemContainer.setVisibility(View.VISIBLE);
        LogUtils.d("聊天服务器已断开");
    }

    private void refreshConversation() {
        EventBus.getDefault().post(new EventMessage("chat_count"));
        subscribe(Observable.create((ObservableOnSubscribe<List<EMConversation>>) emitter -> {
            emitter.onNext(loadConversationList());
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    if (mListAdapter != null) {
                        mListAdapter.addChatData(result, true);
                        // refreshKeeperConversation();
                    }
                }, error -> {
                    LogUtils.e("error-------------------->" + error.getMessage());
                    showMessage("数据获取失败!");
                }));

    }

    /**
     * load conversation list
     *
     * @return +
     */
    private List<EMConversation> loadConversationList() {
        // get all conversations
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        /*
         * lastMsgTime will change if there is new message during sorting
         * so use synchronized to make sure timestamp of last message won't change.
         */
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    String keeperHxName = getApp().getUserInfo().getKeeperHxName();
                    if (!StringUtils.isEmpty(keeperHxName) && conversation.conversationId().equals(keeperHxName)) {
                        setKeeperConversation(conversation);
                        continue;
                    }
                    sortList.add(new Pair<>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        //groupConversationList = new ArrayList<>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            //  if (!sortItem.second.isGroup()) {
            list.add(sortItem.second);
            // } else {
            //     groupConversationList.add(sortItem.second);
            //}
        }
        // refreshUnreadGroup();

        return list;
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, (con1, con2) -> {

            if (con1.first.equals(con2.first)) {
                return 0;
            } else if (con2.first.longValue() > con1.first.longValue()) {
                return 1;
            } else {
                return -1;
            }
        });
    }

    private void setKeeperConversation(EMConversation conversation) {
        subscribe(Observable.create((ObservableOnSubscribe<EMConversation>) emitter -> {
            emitter.onNext(conversation);
        }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                    MessageMultiItemEntity keeperEntity = new MessageMultiItemEntity();
                    keeperEntity.setKeeperConversation(result);
                    keeperEntity.setItemType(MessageMultiItemEntity.KEEPER);
                    mListAdapter.setData(0, keeperEntity);

                    mListAdapter.refreshKeeperChat();
                }));
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        refreshConversation();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }
}
